using System;

namespace ActiveSupport.Access
{
    public static class ArrayAccessExtensions
    {
        public static T[] Except<T>(this T[] list, int elementToExclude)
        {
            var result = new T[list.Length - 1];
            var index = 0;
            for (var i = 0; i < list.Length; i++)
            {
                if (i != elementToExclude)
                {
                    result[index] = list[i];
                    index++;
                }
            }
            return result;
        }

        public static T First<T>(this T[] list)
        {
            if (list == null)
                throw new ArgumentNullException("list");

            return list[0];
        }

        // TODO: should probably move this to an Inflections extension class or something

        public static T[] From<T>(this T[] list, int from)
        {
            if (list == null)
                throw new ArgumentNullException("list");

            var length = list.Length;

            if (from < 0)
                throw new ArgumentOutOfRangeException("from", "Cannot be negative");

            if (from >= length)
                return new T[0];

            var result = new T[length - from];
            var index = 0;
            for (var i = from; i < length; i++)
            {
                result[index++] = list[i];
            }
            return result;
        }

        public static T[] To<T>(this T[] list, int to)
        {
            if (list == null)
                throw new ArgumentNullException("list");

            var length = list.Length;

            if (to >= (length - 1))
                to = length - 1;

            var result = new T[to + 1];
            for (var i = 0; i <= to; i++)
            {
                result[i] = list[i];
            }
            return result;
        }

        public static string Join(this string[] strings)
        {
            return string.Join("", strings);
        }
    }
}